<template>
  <div class="login-wrapper">
    <el-form
      label-width="100px"
      :model="loginForm"
      ref="loginFormRef"
      label-position="right"
      :rules="rules"
    >
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="loginForm.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input
          v-model="loginForm.password"
          placeholder="请输入密码"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱验证码" prop="emailCode">
        <div class="captcha-box">
          <el-input
            v-model="loginForm.emailCode"
            placeholder="请输入邮箱验证码"
          ></el-input>
          <el-button type="primary" round :disabled="timer !== null" @click="sendEmail">{{
            btnText
          }}</el-button>
        </div>
      </el-form-item>
      <el-form-item label="验证码" prop="captcha">
        <div class="captcha-box">
          <el-input v-model="loginForm.captcha" placeholder="请输入验证码"></el-input>
          <img class="captcha-img" @click="reflectCaptcha" :src="captchaImgUrl" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(loginFormRef)">登录</el-button>
        <el-button type="primary" @click="toRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref, Ref, reactive } from "vue";
import { LoginFormType } from "@/type/user";
import { UseCaptcha } from "@/commons/hooks/captcha";
import { ElMessage } from "element-plus";
import { useRouter, Router } from "vue-router";
import type { ElForm } from "element-plus";
type FormInstance = InstanceType<typeof ElForm>;
import { email, password, captcha, emailCode } from "../rules/userRules";
import { $http } from "@/util/ajax";
import md5 from "MD5";

function useLoginForm(loginForm: LoginFormType, router: Router) {
  const loginFormRef = ref<FormInstance>();
  // 登录
  function onSubmit(formEl: FormInstance | undefined): void {
    if (!formEl) return;
    formEl.validate((valid) => {
      if (valid) {
        let obj = {
          ...loginForm,
          password: md5(loginForm.password),
        };
        $http.post("/user/login", obj).then((res: any) => {
          if (res.code === 0) {
            // 保存token
            localStorage.setItem("token", res.data.token);
            // 跳转主页
            router.push("/");
            ElMessage.success(`${res.data.username}, 欢迎回来！！！`);
          } else {
            ElMessage.error(res.message);
          }
        });
      } else {
        ElMessage.error("信息验证不通过");
      }
    });
  }

  return {
    loginFormRef,
    onSubmit,
  };
}

function useEmail(loginForm: LoginFormType) {
  let timer: Ref<any> = ref(null);
  let timerNum: Ref<number> = ref(60);
  const btnText = computed(() => {
    if (timer.value === null) {
      return "发送邮件";
    }
    return `${timerNum.value}s后重新发送`;
  });

  function sendEmail() {
    if (timer.value !== null) {
      return;
    }

    $http.get("/sendcode?email=" + loginForm.email).then((res: any) => {
      if (res.code === 0) {
        return ElMessage.success(res.msg);
      }

      ElMessage.error(res.msg);
    });
    timer.value = setInterval(() => {
      timerNum.value--;
      if (timerNum.value <= 0) {
        clearInterval(timer.value);
        timer.value = null;
        timerNum.value = 60;
      }
    }, 1000);
  }

  return {
    timer,
    btnText,
    sendEmail,
  };
}

export default defineComponent({
  setup() {
    // 登录信息
    const loginForm: LoginFormType = reactive({
      email: "2921855939@qq.com",
      password: "123456",
      captcha: "",
      emailCode: "",
    });

    // 规则
    const rules = reactive({ email, password, captcha, emailCode });

    const router: Router = useRouter();
    // 注册
    function toRegister() {
      router.push("/register");
    }

    // 登录
    const { loginFormRef, onSubmit } = useLoginForm(loginForm, router);

    // 邮件部分
    const { timer, btnText, sendEmail } = useEmail(loginForm);

    // 验证码部分
    const { captchaImgUrl, reflectCaptcha } = UseCaptcha();

    return {
      rules,
      toRegister,
      sendEmail,
      btnText,
      loginFormRef,
      onSubmit,
      reflectCaptcha,
      captchaImgUrl,
      loginForm,
      timer,
    };
  },
});
</script>

<style lang="scss" scope>
.login-wrapper {
  width: 500px;
  margin: 200px auto;

  .captcha-box {
    display: flex;
    justify-content: space-between;

    .captcha-img {
      min-width: 100px;
    }
  }
}
</style>
